package com.wistech.solr.elevation;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import com.alibaba.fastjson.JSON;
import com.wistech.utils.JedisFactory;

public class RedisElevation {
	public static final int NONE_REDIS_PORT = -1;
	private JedisFactory jedisFactory;
	private String elevationName;

	public RedisElevation(String redisHost, String elevationName) {
		this(redisHost, NONE_REDIS_PORT, elevationName);
	}

	public RedisElevation(String redisHost, int redisPort, String elevationName) {
		this(redisHost, NONE_REDIS_PORT, 0, elevationName);
	}

	public RedisElevation(String redisHost, int redisPort, int dbIndex,
			String elevationName) {
		JedisPool jedisPool = null;
		if (NONE_REDIS_PORT == redisPort) {
			jedisPool = new JedisPool(new JedisPoolConfig(), redisHost);
		} else {
			jedisPool = new JedisPool(new JedisPoolConfig(), redisHost,
					redisPort);
		}
		jedisFactory = new JedisFactory();
		jedisFactory.setJedisPool(jedisPool);
		jedisFactory.setDbIndex(dbIndex);
		this.elevationName = elevationName;
	}

	public RedisElevation(JedisPool jedisPool, String elevationName) {
		jedisFactory = new JedisFactory();
		jedisFactory.setJedisPool(jedisPool);
		this.elevationName = elevationName;
	}

	public Map<String, List<Elevation>> getAll() {
		Map<String, List<Elevation>> elevationMap = new HashMap<String, List<Elevation>>();
		Jedis jedis = jedisFactory.getJedis();
		try {
			Map<String, String> map = jedis.hgetAll(elevationName);
			for (Map.Entry<String, String> entry : map.entrySet()) {
				String qstr = entry.getKey();
				String json = entry.getValue();
				List<Elevation> elevations = JSON.parseArray(json,
						Elevation.class);
				if (elevations != null && !elevations.isEmpty()) {
					elevationMap.put(qstr, elevations);
				}
			}
			return elevationMap;
		} finally {
			jedisFactory.returnJedis(jedis);
		}
	}

	public List<Elevation> get(String qstr) {
		Jedis jedis = jedisFactory.getJedis();
		try {
			String json = jedis.hget(elevationName, qstr);
			return JSON.parseArray(json, Elevation.class);
		} finally {
			jedisFactory.returnJedis(jedis);
		}
	}

	public void save(String key, List<Elevation> elevations) {

	}
}
